Date.prototype.Format = function(format){
    var o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(), //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3), //quarter
        "S" : this.getMilliseconds() //millisecond
    }

    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }

    for(var k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
}
var $ = jQuery.noConflict();
var wsTypesObj = {
    'depth': {
        1: 'ok_sub_spot_eth_depth_5_merge_0.1',
        2: 'ok_sub_spot_eth_depth_5_merge_0.1'
    },
    'userInfo': {
        1: 'ok_sub_spotcny_userinfo',
        2: 'ok_sub_spotusd_userinfo'
    },
    'order': {
        1: 'ok_sub_spotcny_trades',
        2: 'ok_sub_spotusd_trades'
    }
};

var webSocket=new WebSocketUtil(site_flag);

webSocket.addSuccCallBackFun(function(){
    $("#deptMerge_stock_btn").unbind('click').click(function (e) {
        var mergeType = wsTypesObj['depth'][site_flag];
        var $target = $(e.target).parent();
        var deptMerge = getCookieValue("deptMerge_stock");
        if (+deptMerge) {
            webSocket.send("ok_sub_spot_eth_depth_5", function(data){
                ethEntrustDepth5Render(data); //console.log('ok_sub_spot_eth_depth_5', data);
            });
            webSocket.stop(mergeType);
            $target.find("IMG:eq(0)").css("display","").siblings().css("display","none");
            setCookieValue("deptMerge_stock", 0);
        } else {
            webSocket.send(mergeType, function(data){
                ethEntrustDepth5Render(data); //console.log(mergeType, data);
            });
            webSocket.stop("ok_sub_spot_eth_depth_5");
            $target.find("IMG:eq(0)").css("display","none").siblings().css("display","");
            setCookieValue("deptMerge_stock", 1);
        }
    });

    // 登录
    var userId = getCookieValue("coin_session_user_id");
    if (userId) {
        webSocket.login(userId);
    }

    // 个人信息
    webSocket.addCallBack(wsTypesObj['userInfo'][site_flag], function(data){
        wsRefreshUserAccountCommon(data);
    });

    // 变化的eth委托单
    webSocket.addCallBack(wsTypesObj['order'][site_flag], function (data) {
        ethEntrustUndealListRender(data, 2);// 在当前页面中增加或删除
    });

    // 最新行情 btc, ltc, eth
    webSocket.send("ok_sub_spot_eth_ticker", function (data) {
        dealSpotEthTicker(data);
        $("#tradeLastPrice").html(data.last ? data.last : '');
    });
    webSocket.send("ok_sub_spot_btc_ticker", function (data) {
        dealSpotBtcTicker(data);
    });
    webSocket.send("ok_sub_spot_ltc_ticker", function (data) {
        dealSpotLtcTicker(data);
    });

    // 5档委托
    var deptMerge = getCookieValue("deptMerge_stock");
    var deptType = +deptMerge ? wsTypesObj['depth'][site_flag] : "ok_sub_spot_eth_depth_5";
    webSocket.send(deptType, function(data){
        ethEntrustDepth5Render(data);
    });
});

// 轮询通过被动调用
webSocket.addErrCallBackFun(function(){
    console.log('addErrCallBackFun');
    //ticker
    handleTicker();

    // 基本信息
    refreshTradeBaner();

    // eth最近十档未成交列表。（历史委托会直接返回，详见函数实现）
    refrushRecord_push_pack();

    // 刷新买一卖五。与下方二选一
    // handleEntrust();

    $("#deptMerge_stock_btn").unbind('click').click(function (e) {
        var $target = $(e.target).parent();
        var deptMerge = getCookieValue("deptMerge_stock");
        if (+deptMerge) {
            setCookieValue("deptMerge_stock", 0);
            $target.find("IMG:eq(0)").css("display","").siblings().css("display","none");
            refreshTradeFullPub(0);
        } else {
            $target.find("IMG:eq(0)").css("display","none").siblings().css("display","");
            setCookieValue("deptMerge_stock", 1);
            refreshTradeFullPub(1);
        }
    });
    var deptMerge = getCookieValue("deptMerge_stock");
    refreshTradeFullPub(+deptMerge ? 1 : 0);
});

webSocket.connection();

function refreshTradeFullPub(deptMerge) {
    // eth五档委托
    jQuery.post("/trade/refreshTradeFullPub.do", {
        symbol: 2,
        deptMerge: deptMerge,
        depthSize: 5,
        tradeSize: 0
    }, function(data){
        var retObj = {
            bids: [],
            asks: [],
            last_price: ''
        };
        // 委托买入五档
        for(var i = 0; i < data.buyDepthList.length; i++){
            if (data.buyDepthList[i] && data.buyDepthList[i].length) {
                retObj.bids.push([data.buyDepthList[i][0], data.buyDepthList[i][1]]);
            }
        }
        // 委托卖出五档
        for(var i = 0; i < data.sellDepthList.length; i++){
            if (data.sellDepthList[i] && data.sellDepthList[i].length) {
                retObj.asks.push([data.sellDepthList[i][0], data.sellDepthList[i][1]]);
            }
        }
        retObj.last_price = data.last_price;
        ethEntrustDepth5Render(retObj);
    },"JSON");
}

// 用于更新eth最近十档未成交列表
function ethEntrustUndealListRender(data, currentSymbol) {
    if (currentSymbol != global.symbol) {
        return;
    }
    // 如果是历史委托，则返回
    var cur = document.getElementById("his_n").className;
    if (cur == "cur")
        return null;
    var tb = document.getElementById("tenorders");    //获取table对像
    var rows = tb.rows;
    var hasRow = false;
    var pushdata = {
        data: data
    };
    if (pushdata.data.tradeType.indexOf("buy") != -1) {
        pushdata.data.tradeType = 1;
    } else {
        pushdata.data.tradeType = 2;
    }
    var entrustSign = SYMBOLS_UTIL.symbolStr[Number(currentSymbol)];
    for (var q = 1; q < rows.length; q++) {    //循环所有的行
        var cells = rows[q].cells;
        var id = cells[0].innerHTML;
        if (id == pushdata.data.id) {//存在相同id
            if (pushdata.data.status == 2 || pushdata.data.status == -1) {//完全成交或撤单
                tb.deleteRow(q);
                if (rows.length == 1) {
                    var trn = tb.insertRow(1);
                    trn.innerHTML = "<td colspan='9' align='center'>" + get$('trade_entrust_ten_yhnoo') + "</td>";
                }
            } else if (pushdata.data.status == 1) {//部分成交
                cells[5].innerHTML = entrustSign + pushdata.data.completedTradeAmount;
                cells[6].innerHTML = cnyOrUsdSymbol + pushdata.data.averagePrice;
                if (pushdata.data.tradeUnitPrice == '1000000' && pushdata.data.tradeType == 1) {
                    cells[7].innerHTML = cnyOrUsdSymbol + pushdata.data.unTrade;
                } else {
                    cells[7].innerHTML = entrustSign + pushdata.data.unTrade;
                }
                cells[8].innerHTML = "(" + get$("trade_entrust_ten_partfulfilled") + ")" + "<a href='javascript:void(0);' onclick='javascript:cancelEntrust(" + pushdata.data.id + ");'>" + get$("trade_entrust_ten_cancel") + "</a>";
            }
            hasRow = true;
            break;
        }
    }
    if (!hasRow) {//新增一行
        if (pushdata.data.status == 2 || pushdata.data.status == -1 || pushdata.data.status == 1) {//完全成交或撤单或部分成交)
            return;
        }
        if (rows.length == 2 && rows[1].cells.length == 1) {
            tb.deleteRow(1);
        }
        var tr = tb.insertRow(1);
        var td = document.createElement("td");
        td.style.cssText = 'display:none';
        td.appendChild(document.createTextNode(pushdata.data.orderId));
        tr.appendChild(td);
        var td = document.createElement("td");
        td.appendChild(document.createTextNode(new Date(pushdata.data.createdDate).Format('yyyy-MM-dd hh:mm:ss')));
        td.setAttribute("class", "gray");
        tr.appendChild(td);
        var td = document.createElement("td");
        if (pushdata.data.tradeType == 1) {
            td.setAttribute("class", "lightgreen5");
        } else {
            td.setAttribute("class", "red");
        }
        td.appendChild(document.createTextNode(pushdata.data.tradeType == '1' ? get$("trade_entrust_ten_bid") : get$("trade_entrust_ten_ask")));
        tr.appendChild(td);
        var td = document.createElement("td");
        if ((pushdata.data.tradeType == 1 && (+pushdata.data.tradeUnitPrice) != 1000000) || pushdata.data.tradeType == 2) {
            td.appendChild(document.createTextNode(entrustSign + pushdata.data.tradeAmount));
        } else {
            td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.tradeAmount));
        }
        tr.appendChild(td);
        var td = document.createElement("td");
        if ((pushdata.data.tradeType == 1 && (+pushdata.data.tradeUnitPrice) != 1000000) || (pushdata.data.tradeType == 2 && +pushdata.data.tradeUnitPrice!= 0)) {
            td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.tradeUnitPrice));
        } else {
            td.appendChild(document.createTextNode(get$("trade_entrust_ten_instant")));
        }
        tr.appendChild(td);
        var td = document.createElement("td");
        td.appendChild(document.createTextNode(entrustSign + pushdata.data.completedTradeAmount));
        tr.appendChild(td);
        var td = document.createElement("td");
        td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.averagePrice));
        tr.appendChild(td);
        var td = document.createElement("td");
        if (pushdata.data.status == 0 || pushdata.data.status == 1 || pushdata.data.status == 3) {
            if (pushdata.data.tradeUnitPrice == '1000000' && pushdata.data.tradeType == 1) {
                td.appendChild(document.createTextNode(cnyOrUsdSymbol + pushdata.data.unTrade));
            } else {
                td.appendChild(document.createTextNode(entrustSign + pushdata.data.unTrade));
            }
        } else {
            td.appendChild(document.createTextNode(pushdata.data.unTrade));
        }
        tr.appendChild(td);
        var td = document.createElement("td");
        td.setAttribute("id", "entrustStatus" + pushdata.data.orderId);
        var statusClass = "";
        var status = "";
        if (pushdata.data.status == 0 || pushdata.data.status == 1 || pushdata.data.status == 3) {
            if (pushdata.data.status == 1) {
                status = "(" + get$("trade_entrust_ten_partfulfilled") + ")";
            } else if (pushdata.data.status == 0) {
                status = "(" + get$("trade_entrust_ten_unfilled") + ")";
            } else if (pushdata.data.status == 3) {
                status = "(" + get$("trade_entrust_ten_unfilled") + ")";
            }
            status = status + "<a href='javascript:void(0);' onclick='javascript:cancelEntrust(" + pushdata.data.orderId + ");'>" + get$("trade_entrust_ten_cancel") + "</a>";
            statusClass = "blue";
        } else if (pushdata.data.status == 2) {
            status = get$("trade_entrust_ten_fulfilled");
            statusClass = "lightgreen5";
        } else {
            status = get$("trade_entrust_ten_cancelled");
            statusClass = "gray";
        }
        td.setAttribute("class", statusClass);
        td.innerHTML = status;
        tr.appendChild(td);
        if (rows.length >= 12) {
            tb.deleteRow(11);
        }

    }
    if (pushdata.data.status == 2) {
        NotifyMsg.showMsg(this.getShowTitle(pushdata.data), getshowMsg(pushdata.data), function () {
            jQuery("#his_n a").click();
        });
    }
    this.getShowTitle = function(order){
        var symbol=jQuery("#symbol").val();
        var msg=SYMBOLS_UTIL.symbolStr2[symbol];
        msg += order.tradeType == 1 ? get$("immediatelybuy") : get$("immediatelysell");
        if(order.tradeUnitPrice == 1000000||order.tradeUnitPrice ==0) {
            msg +=get$("trade_entrust_ten_instant");
        }else{
            msg+=get$("futureplanentrust2");
        }
        msg+=get$("alreadDeall");
        return msg;
    }
}

// 买卖五档委托渲染
function ethEntrustDepth5Render(data) {
    var bids = data.bids;
    var asks = data.asks;
    var bidin = $("#bidin_buy").val();
    var askout = $("#askout_sell").val();

    // 最新价格
    data.last_price ? $("#tradeLastPrice").html(data.last_price) :  '';

    // 卖
    var asksHtml = '';
    if (asks && asks.length) {
        var askLen = asks.length;
        for (var i = asks.length; i > 0; i--) {
            asksHtml += ''
                + '<li class="red" onmouseover="this.style.cursor=\'pointer\';this.style.backgroundColor=\' #FFFFAA\';" onmouseout="this.style.backgroundColor=\' #fff\';" onclick="javascript:autoTrade_new(' + i + ', 1, 2);" >'
                +    '<span class="c1">' + askout + ' (' + i + ')</span>'
                +    '<span class="c2" id="sellPriceSpan' + i + '">' + (+asks[askLen - i][0]).toFixed(2) + '</span>'
                +    '<input id="sellPrice' + i + '" type="hidden" value="' + (+asks[askLen - i][0]).toFixed(2) + '"/>'
                +    '<span class="c3" id="sellAmountSpan' + i + '">' + asks[askLen - i][1] + '</span>'
                +    '<input id="sellAmount' + i + '" type="hidden" value="' + asks[askLen - i][1] + '"/>'
                + '</li>';
        }
        $("#sellList").html(asksHtml);
    }

    // 买
    var bidsHtml = '';
    if (bids && bids.length) {
        for (var i = 0; i < bids.length; i++) {
            bidsHtml += ''
                + '<li class="lightgreen5" onmouseover="this.style.cursor=\'pointer\';this.style.backgroundColor=\' #FFFFAA\';" onmouseout="this.style.backgroundColor=\' #fff\';" onclick="javascript:autoTrade_new(' + (i + 1) + ', 0, 2);" >'
                +    '<span class="c1">' + bidin + ' (' + (i + 1) + ')</span>'
                +    '<span class="c2" id="buyPriceSpan' + (i + 1) + '">' + (+bids[i][0]).toFixed(2) + '</span>'
                +    '<input id="buyPrice' + (i + 1) + '" type="hidden" value="' + (+bids[i][0]).toFixed(2) + '"/>'
                +    '<span class="c3" id="buyAmountSpan' + (i + 1) + '">' + bids[i][1] + '</span>'
                +    '<input id="buyAmount' + (i + 1) + '" type="hidden" value="' + bids[i][1] + '"/>'
                + '</li>';
        }
        $("#buyList").html(bidsHtml);
    }
}

